import unittest

from pserver import server
from common.packets import PacketHandler

class testServer(unittest.TestCase):
    def setUp(self):
        self.server = server.PServer()

    def testSinglePacket(self):
        initial_data = (12, 13, 14)
        initial_id = 1
        packet = self.server.getPacket(initial_id, initial_data)
        return_id, return_data = self.server.handleUnit(packet[1:])
        self.assertEqual(return_id, initial_id)
        self.assertEqual(return_data, initial_data)
        
    def testHandleSingleData(self):
        initial_data = (15, 20, 33)
        initial_id = 200
        packet = self.server.getPacket(initial_id, initial_data)
        unit = self.server.cacheData(packet)
        self.assertEqual(unit[0], initial_id)
        self.assertEqual(unit[1], initial_data)

    def testHandleSplitData(self):
        initial_data = (15, 20, 33)
        initial_id = 200
        packet = self.server.getPacket(initial_id, initial_data)
        unit = None
        for s in packet: #go through byte-by-byte
            unit = self.server.cacheData(s)
        self.assertEqual(unit[0], initial_id)
        self.assertEqual(unit[1], initial_data)
        print "New split..."
        #try only one split with different data
        initial_data = (30, 40, 50)
        initial_id = 150
        packet = self.server.getPacket(initial_id, initial_data)
        unit = self.server.cacheData(packet[0:5])
        self.assertEqual(unit, None) #we shouldnt have data yet
        unit = self.server.cacheData(packet[5:])
        self.assertNotEqual(unit, None)
        self.assertEqual(unit[0], initial_id)
        self.assertEqual(unit[1], initial_data)
        
        

def suite():
    suite = unittest.TestSuite()
    suite.addTest(unittest.makeSuite(testServer))
    return suite

def main():
    unittest.TextTestRunner(verbosity=2).run(suite())

if __name__ == '__main__':
    main()
